import {
    VuexModule,
    Module,
    Action,
    Mutation,
    getModule
} from 'vuex-module-decorators'
import store from '@/store'
import { login, userInfo, logOut } from '@/api/user'
import { removeToken, setToken, getToken } from '@/utils/cookie'

export interface UserState {
    token: string // 用户token
    userInfo: string[] // 用户信息
    userCompany: string[] // 用户公司信息
}

/** 定义模块内容 */
@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements UserState {
    public token = ''
    public userInfo = []
    public userCompany = []

    @Mutation
    private SET_TOKEN(token: string) {
        this.token = token
    }

    @Mutation
    private SET_USERINFO(info: any) {
        this.userInfo = info
    }

    @Mutation
    private SET_USERCOMPANY(info: any) {
        this.userCompany = info
    }

    @Action
    /** 登录 */
    public async Login(userInfo: { username: string; password: string }) {
        // 请求字段formData化
        const params = new FormData()
        params.append('username', userInfo.username)
        params.append('password', userInfo.password)

        // 返回promise便于执行下一步
        return new Promise((resolve, reject) => {
            login(params)
                .then((response: any) => {
                    if (response.code === 0) {
                        const data = response
                        this.SET_TOKEN(data.token)
                        setToken(data.token)
                        resolve(response)
                    }
                })
                .catch((err: any) => {
                    reject(err.response)
                })
        })
    }

    @Action({ rawError: true })
    /** 获取用户信息 */
    public async GetUserInfo() {
        const token = getToken()
        // 保证token的获取
        if (this.token === '') {
            this.SET_TOKEN(token as string)
        }
        const { result } = await userInfo()
        if (!result) {
            throw new Error('你可能需要重新登录一下')
        }
        if (!result.user) {
            throw new Error('用户信息获取失败了')
        }

        // 保存用户信息
        this.SET_USERINFO(result.user)
        // 保存用户的公司信息
        this.SET_USERCOMPANY(result.company)
    }

    @Action({ rawError: true })
    /** 登出 */
    public async LogOut() {
        return new Promise((resolve, reject) => {
            logOut()
                .then((res: any) => {
                    if (res.code === 0) {
                        // 清空当前token和用户数据
                        this.SET_TOKEN('')
                        this.SET_USERINFO([])
                        removeToken()
                    }
                    resolve(res)
                })
                .catch((err: any) => {
                    reject(err)
                })
        })
    }
}

export const userModule = getModule(User)
